﻿namespace FeedbackBrowser
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Windows;

    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.Framework.Client;
    using Microsoft.TeamFoundation.Framework.Common;
    using Microsoft.TeamFoundation.WorkItemTracking;
    using Microsoft.TeamFoundation.WorkItemTracking.Client;

    using Configuration = System.Configuration.Configuration;

    public partial class MainWindow : Window
    {
        #region Fields

        readonly IIdentityManagementService _ims;

        TfsTeamProjectCollection _tfs;

        #endregion Fields

        #region Constructors

        public MainWindow()
        {
            InitializeComponent();
        }

        #endregion Constructors

        #region Methods

        private static List<QueryDefinition> GetAllTeamQueries(Project project, string startFolder)
        {
            var ret = new List<QueryDefinition>();

            var startQueryFolder = GetQueryFolder(project.QueryHierarchy,
                                                  startFolder == null ? (new string[] { }) : startFolder.Split('\\'));

            ret.AddRange(GetAllTeamQueries(startQueryFolder));

            return ret;
        }

        private static List<QueryDefinition> GetAllTeamQueries(QueryFolder queryFolder)
        {
            var ret = new List<QueryDefinition>();

            foreach (QueryItem queryItem in queryFolder)
            {
                if (queryItem is QueryFolder)
                {
                    ret.AddRange(GetAllTeamQueries(queryItem as QueryFolder));
                }
                else
                {
                    ret.Add(queryItem as QueryDefinition);
                }
            }

            return ret;
        }

        private static QueryFolder GetQueryFolder(QueryFolder queryFolder, string[] folders)
        {
            return folders.Length == 0 ? queryFolder : GetQueryFolder((QueryFolder)queryFolder[folders[0]], folders.Skip(1).ToArray());
        }

        private void BtnConnectClick(object sender, RoutedEventArgs e)
        {
            string _myUri = @"https://latek.tfspreview.com";

            //TfsTeamProjectCollection projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(_myUri));
            //WorkItemStore workItemStore = projectCollection.GetService<WorkItemStore>();
            //Project teamProject = workItemStore.Projects[1];

            TfsConfigurationServer configurationServer =
                            TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri));

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection<CatalogNode> tpcNodes = catalogNode.QueryChildren(
                            new Guid[] { CatalogResourceTypes.ProjectCollection },
                            false, CatalogQueryOptions.None);

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                _tfs = configurationServer.GetTeamProjectCollection(tpcId);

                // Get catalog of tp = 'Team Projects' for the tpc = 'Team Project Collection'
                var tpNodes = tpcNode.QueryChildren(
                          new Guid[] { CatalogResourceTypes.TeamProject },
                          false, CatalogQueryOptions.None);

                foreach (var p in tpNodes)
                {
                    Debug.Write(Environment.NewLine + " Team Project : " + p.Resource.DisplayName + " - " + p.Resource.Description + Environment.NewLine);
                }
            }

            //var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("https://latek.tfspreview.com"));

            //Uri tfsUri = new Uri("https://latek.tfspreview.com/");
            //const string projectName = "TFSRenamer";

            // Load the tfs instance
            //TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(tfsUri, new UICredentialsProvider());

            // Log in to TFS
               // tfs.Authenticate();

            //TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            //tpp.ShowDialog();

            //if (tpp.SelectedTeamProjectCollection != null)
            //{
            //    _tfs = tpp.SelectedTeamProjectCollection;
            //    txtCollection.Text = _tfs.Name.Split(new char[] { '\\' })[1];
            //    txtProjectName.Text = tpp.SelectedProjects[0].Name;

            //    btnRenameProject.IsEnabled = true;

            //}

            //var wiStore = _tfs.GetService<WorkItemStore>();
            //var project = wiStore.Projects[tpp.SelectedProjects[0].Name];

            //string startFolder = null;
            //foreach (QueryDefinition queryDefinition in GetAllTeamQueries(project, startFolder))
            //{
            //}

            var wis = _tfs.GetService<WorkItemStore>();

            var teamProject = wis.Projects["TFSRenamer"];

            var qBug = @" SELECT [System.Id], [System.WorkItemType]," +
             " [System.State], [System.AssignedTo], [System.Title] " +
             " FROM WorkItems " +
             " WHERE [System.TeamProject] = '" + teamProject.Name +
            "' AND [System.WorkItemType]='Feedback Request' and [System.AssignedTo] =@me ORDER BY [System.WorkItemType], [System.Id]";

            // Get the Wi Store service

            var queryBug = new Query(wis, qBug);
            var bugs = queryBug.RunQuery();

            // 2. Get the Uri of the session from the bug
            foreach (WorkItem bug in bugs)
            {
                foreach (Link l in bug.Links)
                {
                }
            }
        }

        private void btnRenameProject_Click(object sender, RoutedEventArgs e)
        {
            ExecuteRenameScript();
        }

        private void ExecuteRenameScript()
        {
            //try
            //{

            //    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = Properties.Settings.Default.WebConfigFileLocation };

            //    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            //    string connstring = string.Empty;
            //    if (configuration.AppSettings.Settings.Count > 0)
            //    {
            //        System.Configuration.KeyValueConfigurationElement customSetting =
            //            configuration.AppSettings.Settings["applicationDatabase"];
            //        if (customSetting != null)
            //            connstring = customSetting.Value;
            //    }

            //    FileInfo file = new FileInfo(System.Environment.CurrentDirectory + "\\RenameTFS Project.sql");
            //    string script = file.OpenText().ReadToEnd();

            //    script = script.Replace("OLDNAME", txtProjectName.Text);
            //    script = script.Replace("NEWNAME", txtNewProjectName.Text);

            //    script = script.Replace("Tfs_DefaultCollection", "Tfs_" + txtCollection.Text);

            //    //SqlConnection conn = new SqlConnection(connstring);
            //    //Server server = new Server(new ServerConnection(conn));
            //    //server.ConnectionContext.ExecuteNonQuery(script);
            //    //MessageBox.Show("Renaming finished successfully. Thank you for using TFS Renamer !!!");

            //}
            //catch (Exception ex)
            //{

            //    MessageBox.Show(ex.ToString());
            //}
        }

        #endregion Methods
    }
}